<?php

namespace App\Services\Api;

use App\Models\ClassBase;
use App\Models\ClassBaseInfo;
use App\Models\ClassBaseTime;
use App\Models\StoreRegion;
use App\Models\Store;
use App\Models\UserSubscribe;
use App\Models\ClassBaseInfoSuspension;
use App\Models\ClassQuarterly;
use App\Services\Admin\Reservation;
use Illuminate\Support\Facades\Log;

class ClassService
{
    //首页课程列表
    public static function class_home_lists($param = [])
    {
        if (!empty($param['store_id'])) {
            $store_id = explode(';', $param['store_id']);
        }

        $class = (new ClassBase());
        if (isset($store_id)) $class = $class->whereIn('store_id', $store_id);
        $class = $class->select('class_name', 'id', 'class_price', 'class_tab', 'class_cove', 'class_name', 'original_price')->paginate(6);

        return $class;
    }

    //课程详情
    public static function class_home_info($param = [])
    {
        $result = ClassBase::with(['carousel_image'])->where('id', $param['class_id'])->select(
            'class_cove', 'class_name', 'created_at', 'updated_at', 'class_tab', 'class_clothing', 'class_faq', 'class_note', 'class_introduction', 'class_price', 'id', 'original_price')
            ->first()
            ->toArray();

        $result['carousel_image'] = array_column($result['carousel_image'], 'image');

        return $result;
    }

    //課程安排詳情
    public static function class_base_info_detail($id, $data_time)
    {
        if (!empty($data_time)) {
            $day = date('Y-m-d', strtotime("{$data_time}"));
        } else {
            $day = date('Y-m-d', time());
        }

        $result = ClassBaseInfo::where('id', $id)
            ->with([
                'class_base',
                'teacher' => function ($q) {
                    $q->select([
                        'id',
                        'teacher_name',
                        'teacher_head',
                        'synopsis',
                    ]);
                },
                'classsroom' => function ($q) {
                    $q->select([
                        'id',
                        'numbering',
                        'number',
                    ]);
                },
                'store' => function ($q) {
                    $q->select([
                        'id',
                        'store_name',
                        'province',
                        'city',
                        'area',
                        'store_address',
                    ]);
                }
            ])->first()->toArray();

        $class_bass_info_teacher_arr = Reservation::class_bass_info_teacher_result($id)->get()->toArray();

        $teacher_bool_info = Reservation::class_bass_info_teacher_arr($class_bass_info_teacher_arr, $day);

        $result['teacher'] = $teacher_bool_info;

        $result['class_base']['class_price'] = round($result['class_base']['class_price']);
        $result['class_base']['original_price'] = round($result['class_base']['original_price']);
        return $result;
    }

    //课程 安排列表
    public static function class_base_info($param = [])
    {

        date_default_timezone_set('PRC');

        if (!empty($param['class_base_id'])) $class_base_id = explode(';', $param['class_base_id']);

        if (!empty($param['store_id'])) $store_id = explode(';', $param['store_id']);

        if (!empty($param['time_id'])) $time_id = explode(';', $param['time_id']);

        if (!empty($param['data_time'])) {
            $start_time = date('Y-m-d 00:00:00', strtotime("{$param['data_time']}"));
            $start_time_date = date('Y-m-d', strtotime("{$param['data_time']}"));
            $end_time = date('Y-m-d 23:59:59', strtotime("{$param['data_time']}"));
            $day = date('Y-m-d', strtotime("{$param['data_time']}"));
        } else {
            $start_time = date('Y-m-d 00:00:00', time());
            $start_time_date = date('Y-m-d', time());
            $end_time = date('Y-m-d 23:59:59', time());
            $day = date('Y-m-d', time());
        }

        $use_integral = '';

        if (!empty($param['user_subscribe_id'])) {
            $use_integral = UserSubscribe::where('id', $param['user_subscribe_id'])->value('use_integral');
        }

        $class_base_info = ClassBaseInfo::with([
            'class_base',
            'teacher',
            'classsroom',
            'store',
            'my_subscribe' => function ($q) use($start_time,$end_time){
                $user_id = !empty(auth('api')->user()) ? auth('api')->user()->id : 0;
                $q->where('user_id', $user_id)
                    ->where('class_time','>=',$start_time)
                    ->where('end_time','<=',$end_time)
                    ->orderBy('id','desc');
            },
            'class_base_info_suspension'
        ])->whereHas('quarterly', function ($quarterly) use($day) {

            $where[] = ['start_time', '<=', $day];
            $where[] = ['end_time', '>=', $day];
            $where[] = ['is_display', 1];

            $quarterly->where($where);

        });

        if (!empty($use_integral)) {
            $class_base_info = $class_base_info->whereHas('class_base', function ($query) use ($use_integral) {
                $query->where('class_price', '<=', $use_integral);
            });
        }

        if (!empty($class_base_id)) $class_base_info = $class_base_info->whereIn('class_base_id', $class_base_id);
        if (!empty($store_id)) $class_base_info = $class_base_info->whereIn('store_id', $store_id);
        if (!empty($time_id)) $class_base_info = $class_base_info->whereIn('class_time_id', $time_id);

        if (!empty($param['class_week']) && !empty($day)) {
            $class_week = explode(';', $param['class_week']);

            $class_week_string = implode(',', $class_week);

            $user_rank_id = auth()->user('api')->user_rank_id;

            $where_raw = "(class_week in ({$class_week_string})) and (user_rank_id like '%{$user_rank_id}%' or user_rank_id is null) and (IF(designated_date != '', designated_date like '%{$day}%',1=1))";

            $class_base_info = $class_base_info->whereRaw($where_raw);
        }

        $class_base_info = $class_base_info
            ->where('is_camp', 2)
            ->orderBy('class_base_info.class_time', 'asc')
            ->get();

        $result = [];

        //查询预约数
        $class_base_info_id = array_column($class_base_info->toArray(), 'id');

        $class_subscribe_number_array = (new UserSubscribe)->ClassSubscribeNumber($class_base_info_id, $start_time, $end_time);

        foreach ($class_base_info as $k => $v) {

            $class_base_info_suspension = [];

            if(!empty($v['class_base_info_suspension'])) {
                $class_base_info_suspension = $v['class_base_info_suspension']->toArray();
            }

            $open_an_appointment = Reservation::current_control_time($class_base_info_suspension, $day);

            if($open_an_appointment == 0) {
                //全局控制是否开启预约
                if ($v['is_display'] == -1)continue;
            }else{
                //部分控制是否开启预约
                if ($open_an_appointment == -1)continue;
            }

            if(isset($class_subscribe_number_array[$v['id']])){

                $class_subscribe_number = $class_subscribe_number_array[$v['id']];

            }else{

                $class_subscribe_number = 0;

            }

            $class_bass_info_teacher_arr = Reservation::class_bass_info_teacher_result($v->id)->get()->toArray();

            $teacher = Reservation::class_bass_info_teacher_arr($class_bass_info_teacher_arr, $day);

            if(empty($teacher['id']))continue;

            $class_time_array = explode('~', $v->class_time);

            $up_class_time = $class_time_array[0]??'';

            $start_time_string = strtotime("{$start_time_date} {$up_class_time}");

            if(!empty($up_class_time)) {
                //判断开启最少人预约问题
                if (!empty($v->start_before_minutes)) {
                    //判断是否够人数开课,不够则不允许预约
                    if (time() > ($start_time_string - ($v->start_before_minutes * 60))) {
                        if ($class_subscribe_number < $v->minimum_number) continue;
                    }
                }
            }

            $input['teacher']['head'] = $teacher['teacher_head']??'';
            $input['teacher']['teacher_id'] = $teacher['id']??'';
            $input['teacher']['name'] = $teacher['teacher_name']??'';
            $input['teacher']['tab'] = $teacher['tab']??'';

            $input['class_info']['button_status'] = self::class_base_button_status($class_subscribe_number, $v);
            $input['class_info']['name'] = $v->class_base->class_name;
            $input['class_info']['class_price'] = round($v->class_base->class_price);
            $input['class_info']['class_id'] = $v->class_base->id;
            $input['class_info']['class_tab'] = $v->class_base->class_tab;
            $input['class_info']['class_time'] = $v->class_time;

            $class_time_array = explode('~', $v->class_time);
            $input['class_info']['start_class_time'] = $class_time_array[0];
            $input['class_info']['end_class_time'] = $class_time_array[1];

            $input['class_info']['class_duration'] = $v->class_duration;
            $input['class_info']['class_week'] = $v->class_week;
            $input['class_info']['class_number_people'] = $v->class_number_people;
            $input['class_info']['class_subscribe_number'] = $class_subscribe_number;
            $input['class_classsroom']['numbering'] = $v->classsroom->numbering;
            $input['class_classsroom']['class_img'] = $v->classsroom->class_img;
            $input['class_classsroom']['image'] = $v->classsroom->image;
            $input['class_info_id'] = $v->id;

            $result[$v->store_id]['lists'][] = $input;
            $result[$v->store_id]['store_name'] = $v->store->store_name;

        }

        return array_values($result);

    }

    /**
     * 用作输出结果
     * button_status 1已结束 2已预约 3已排队 4已开始 5可预约 6可排隊 -2已預約/已排隊
     * @param int       $class_subscribe_number     已预约人数
     * @return string
     */
    public static function class_base_button_status($class_subscribe_number = 0, $v = '')
    {
        $data_time = request()->input('data_time');

        $button_status = '';

        //返回状态按钮
        $time = explode('~', $v->class_time);

        $class_time_start = "{$data_time} $time[0]:00";

        $class_time_end = "{$data_time} $time[1]:00";

        $new_time = time();

        //subscribe_status  '预约状态 1排队中 2预约成功 3预约失败 4预约取消 5上课完成 6請假 7已选择补课'

        //未开始
        if($new_time < strtotime($class_time_start)){

            if(!empty($v->my_subscribe)) {
                //已签到
                if ($v->my_subscribe->subscribe_status == 5) return -2;

                //已请假
                if ($v->my_subscribe->subscribe_status == 6) return -6;

                //已预约
                if ($v->my_subscribe->subscribe_status == 2) return 2;

                //已排队
                if ($v->my_subscribe->subscribe_status == 1) return 3;
            }

            if($class_subscribe_number < $v->class_number_people){
                //可预约
                return 5;
            }else{
                //可排队
                return 6;
            }

        }

        //已开始
        if($new_time >= strtotime($class_time_start) && $new_time <= strtotime($class_time_end)){
            return 4;
        }

        //已结束
        if($new_time > strtotime($class_time_end)){
            return 1;
        }

    }

    //条件查询
    public static function where($where_type = '')
    {
        switch ($where_type) {
            case 'class_lists':
                //课程列表
                return self::class_lists();
                break;
            case 'store_lists':
                //门店列表
                return self::store_lists();
                break;
            case 'time_lists':
                //时间段列表
                return self::time_lists();
                break;
        }
    }

    //课程列表
    public static function class_lists()
    {
        return (new ClassBase())->where('class_popular', '1')->select('class_name', 'id')->get();
    }

    //门店
    public static function store_lists()
    {

        $store_region = (new Store())->all();

        foreach ($store_region as $v) {
            $input['name'] = $v->store_name;
            $input['id'] = $v->id;
            $store_region_key[$v->city . '-' . $v->area][] = $input;
            unset($input);
        }

        //门店地址
        $store_region = (new StoreRegion())->all();

        foreach ($store_region as $v) {
            $city_result[$v->city][] = $v->area;
        }

        $result = [];

        foreach ($city_result as $k => $v) {

            $input = [];
            $input['city'] = $k;

            foreach ($city_result[$k] as $vv) {

                $region = [];
                $region['area_name'] = $vv;
                $region['store_lists'] = $store_region_key[$k . '-' . $vv] ?? [];

                $input['region'][] = $region;

            }

            $result[] = $input;

        }

        return $result;
    }

    //时段
    public static function time_lists()
    {

        $result = (new ClassBaseTime())->all();

        foreach ($result as &$v) {

            $v->time_name = "{$v->time_start}~{$v->time_end}";

            unset($v->time_start);
            unset($v->time_end);

        }

        return $result;
    }


}
